import TableContainer from "@/components/TableContainer"
import useTableSelector from "@/components/useTableSelector"
import { PAGINATION_CONFIG } from "@/constants"
import { CategoryType } from "@/constants/enums/category"
import { GoodsState, GoodsType } from "@/constants/enums/goods"
import { queryCategory } from "@/services/common"
import { queryGoodsList, saveGoods, delGoods } from "@/services/goods"
import { enum2options } from "@/utils/enum2options"
import { useRequest } from "ahooks"
import { Button, Checkbox, Col, Form, Input, InputNumber, Modal, Popconfirm, Row, Select, Space, Table, Tabs, message } from "antd"
import { ColumnsType } from "antd/es/table"
import { useMemo, useState } from "react"
import { history, Access } from '@umijs/max'
import dayjs from "dayjs"
import { EditFilled, EditOutlined } from "@ant-design/icons"
import TableActions from "@/components/TableActions"

const Device: React.FC<RoutePageProps> = () => {
  const [searchForm] = Form.useForm()
  const [searchParams, setSearchParams] = useState<Goods.QueryListParams>({
    pageNum: 1, pageSize: 10, goodsType: GoodsType.基础商城,
  });
  const [checkAllLeftPadding, setCheckAllLeftPadding] = useState(8)
  const category = useRequest(() => queryCategory({type: CategoryType.商城}))
  const goodsList = useRequest(() => queryGoodsList(searchParams), {
    refreshDeps: [searchParams],
    onSuccess: () => {
      setTimeout(() => {
        const selectionDom = document.querySelector('.ant-table-selection-column')
        if (selectionDom) {
          setCheckAllLeftPadding((selectionDom.clientWidth - 16) / 2)
        }
      }, 10)
    }
  })
  const { getSelected, setSelected, effect } = useTableSelector()
  const [tabKey, setTabKey] = useState('all')
  const saveReq = useRequest(saveGoods, {manual: true})
  const delReq = useRequest(delGoods, {manual: true})

  const onFinish = (values: any) => {
    setSearchParams({
      ...searchParams,
      goodsName: values.goodsName,
      state: values.goodsState,
      pageNum: 1,
    })
  }
  const jump2editPage = (id?: string) => {
    sessionStorage.setItem('needRefresh', 'yes')
    sessionStorage.setItem('__/mall/physical/goods/add_title', id ? '编辑商品' : '新建商品')
    history.push(`/mall/physical/goods/add?id=${id || ''}`)
  }
  const onTabKeyChange = (key: string) => {
    setTabKey(key)
    setSearchParams({
      ...searchParams,
      category: key === 'all' ? undefined : key,
      pageNum: 1,
    })
  }
  const offGoods = async (record: Goods.Entity) => {
    return saveReq
    .runAsync({goodsId: record.goodsId, goodsState: GoodsState.下架})
    .then(() => {
      message.success('下架成功')
      goodsList.refresh()
    })
  }
  const onGoods = async (record: Goods.Entity) => {
    return saveReq
    .runAsync({goodsId: record.goodsId, goodsState: GoodsState.上架})
    .then(() => {
      message.success('上架成功')
      goodsList.refresh()
    })
  }
  const _delGoods = async (record: Goods.Entity) => {
    return delReq
    .runAsync({goodsId: record.goodsId})
    .then(() => {
      message.success('删除成功')
      goodsList.refresh()
    })
  }
  const updateOrder = async (record: Goods.Entity) => {
    let _order: number | null = record.goodsOrder || 0
    Modal.confirm({
      icon: <EditFilled />,
      title: '修改权重',
      content: <InputNumber
        placeholder="权重" style={{width: '100%'}}
        defaultValue={_order} min={0} precision={0} controls={false}
        onChange={val => _order = val}
      />,
      onOk: async () => {
        if (_order === null) {
          message.error('请输入有效的权重')
          return Promise.reject()
        }
        return saveReq
          .runAsync({goodsId: record.goodsId, goodsOrder: _order})
          .then(() => {
            message.success('修改成功')
            goodsList.refresh()
          })
      }
    })
  }

  const columns: ColumnsType<Goods.Entity> = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      width: 300,
    },
    {
      title: '价格(元)',
      dataIndex: 'goodsPrice',
      width: 100,
    },
    {
      title: '库存',
      dataIndex: 'goodsNum',
      width: 100,
    },
    {
      title: '销量',
      dataIndex: 'sale',
      width: 100,
    },
    {
      title: '权重',
      dataIndex: 'goodsOrder',
      width: 100,
      render: (val, record) => {
        return <div className="flex items-center gap-2 group">
          <div>{val}</div>
          <div className="hidden group-hover:flex cursor-pointer" onClick={() => updateOrder(record)}>
            <EditOutlined />
          </div>
        </div>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 160,
      render: val => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '--',
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      width: 160,
      render: val => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '--',
    },
    {
      title: '商品状态',
      dataIndex: 'goodsState',
      width: 120,
      render: val => {
        switch (val) {
          case GoodsState.上架: return '上架'
          case GoodsState.下架: return '下架'
          default: return '--'
        }
      }
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 200,
      render: (_, record) => {
        return (
          <TableActions>
            <a key='edit' onClick={() => jump2editPage(record.goodsId)}>编辑</a>
            <Access accessible={record.goodsState === GoodsState.上架}>
              <Popconfirm title='确认下架该商品吗？' onConfirm={async () => offGoods(record)}>
                <a>下架</a>
              </Popconfirm>
            </Access>
            <Access accessible={record.goodsState === GoodsState.下架}>
              <Popconfirm title='确认上架该商品吗？' onConfirm={async () => onGoods(record)}>
                <a>上架</a>
              </Popconfirm>
            </Access>
            <Access accessible={record.goodsState === GoodsState.下架}>
              <Popconfirm title='确认删除该商品吗？' onConfirm={async () => _delGoods(record)}>
                <a>删除</a>
              </Popconfirm>
            </Access>
          </TableActions>
        )
      }
    },
  ]

  const onCheckAllChange = (checked: boolean) => {
    setSelected(searchParams.pageNum, checked ? (goodsList.data?.data || []).map(item => item.goodsId) : [])
  }

  const checkAll = useMemo(() => {
    let currentTotal = goodsList.data?.data?.length || 0
    let currentSelectedTotal = getSelected(searchParams.pageNum).length
    return {
      checked: currentSelectedTotal === currentTotal,
      indeterminate: currentSelectedTotal > 0 && currentSelectedTotal < currentTotal
    }
  }, [goodsList.data, effect, searchParams])

  return (
    <TableContainer>
      <TableContainer.Toolbar>
        <Button type='primary' onClick={() => jump2editPage()}>新建商品</Button>
      </TableContainer.Toolbar>
      <TableContainer.SearchContainer>
        <Form colon={false} name='searchStationListForm' form={searchForm} onFinish={onFinish}>
          <Row gutter={[20, 20]}>
            <Col span={6}>
              <Form.Item label='商品名称' name='goodsName'>
                <Input placeholder='请输入' variant='borderless' />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label='商品状态' name='goodsState'>
                <Select placeholder='请选择' variant='borderless' options={enum2options(GoodsState)} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Space>
                <Button type='primary' htmlType='submit' loading={goodsList.loading}>筛选</Button>
                <Button htmlType='reset'>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </TableContainer.SearchContainer>
      <Tabs
        items={[
          {label: '全部', key: 'all'},
          ...(category.data?.data.map(it => ({label: it.categoryName, key: String(it.categoryId)})) || []),
        ]}
        activeKey={tabKey}
        onChange={onTabKeyChange}
        tabBarExtraContent={{
          left: <div style={{padding: 8}}></div>
        }}
      />
      <Table<Goods.Entity>
        rowKey='goodsId'
        loading={goodsList.loading}
        dataSource={goodsList.data?.data}
        columns={columns}
        scroll={{y: 700, x: 'max-content'}}
        // rowSelection={{
        //   selectedRowKeys: getSelected(searchParams.pageNum),
        //   onChange: (rowKeys) => setSelected(searchParams.pageNum, rowKeys),
        // }}
        pagination={{
          ...PAGINATION_CONFIG,
          current: searchParams.pageNum,
          pageSize: searchParams.pageSize,
          total: goodsList.data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              pageNum: page === searchParams.pageNum ? 1 : page,
              pageSize,
            })
          },
          // position: ['bottomRight', 'topLeft'],
          showTotal: total => [
            // <Space key='selection' style={{paddingLeft: checkAllLeftPadding}}>
            //   <Checkbox
            //     checked={checkAll.checked}
            //     indeterminate={checkAll.indeterminate}
            //     onChange={({target}) => onCheckAllChange(target.checked)}
            //   >当页全选</Checkbox>
            //   {/* <Button onClick={openPriceDrawer}>设置电价</Button> */}
            // </Space>,
            <div key='total' className="ml-auto">{`共${total}条`}</div>,
          ],
        }}
      />
    </TableContainer>
  )
}

export default Device
